<?php
// declare (strict_types = 1);
namespace app\api\controller;

use app\model\Token;
use app\model\OpAccount;
use app\model\ViewItem;
use app\model\ItemConsume;
use app\model\Recharge;
use app\model\Items;
use think\facade\Log;
use think\facade\Db;
use think\db\Where;
use app\model\AccInfo;
class Index
{
    
    function text(){
    
        /* $c = app('http')->getName();
        dump($c); */
        return view();
    }
    //
    public function index()
    {
        $r = Token::where('group','ziapi')->cache('zi_token')->find();
        
        $headers = array( 'Content-Type:application/json');
        $url = 'https://ad.oceanengine.com/open_api/oauth2/advertiser/get/?app_id='.C('zj_app_id').'&secret='.C('zj_secret').'&access_token='.$r['access_token'];
        
        $rs = json_decode(http_get($url,$headers),true);
        
        dump($rs);
        //return '您好！这是一个[api]示例应用';
    }
    function get_adv(){
        $r = Token::where('group','ziapi')->cache('zi_token')->find();
        $arr = explode(",", $r['advertiser_ids']);
        $headers = array( 'Access-Token:'.$r['access_token']);
        if(count($arr)>1){
            
            $url = 'https://ad.oceanengine.com/open_api/2/majordomo/advertiser/select/?advertiser_id='.$r['advertiser_ids'];
        }else{
            $url = 'https://ad.oceanengine.com/open_api/2/majordomo/advertiser/select/?advertiser_id='.$r['advertiser_ids'];
        }
        
        dump($url);
        
    }
    //获取授权账户 跟新账户授权
    public function zj_accredit_acc(){
        $r = Token::where('group','ziapi')->cache('zi_token')->find();
        $headers = array( 'Access-Token:'.$r['access_token']);
        $url = 'https://ad.oceanengine.com/open_api/2/majordomo/advertiser/select/?advertiser_id=1673544543768589';  //1678948648340487   1673544543768589
        $rs = json_decode(http_get($url,$headers),true);
        if($rs['code'] == 0 ){
            foreach ($rs['data']['list'] as $k=>$v){
                $ids[] = $v['advertiser_id'];
            }
            dump($ids);
    
            //$this->get_acc_is_accredit($ids);
        }
        dump($rs);
         
    }
    //测试
    //获取字节 表单消耗和数量
    public function cs_zj_form_num(){
        set_time_limit(0);
        $wh[] = ['group','=','ziapi'];
        $wh[] = ['acc_id','=','1095'];
        $list = Token::where($wh)->select();
        foreach ($list as $k=>$v){
            $t = date("Y-m-d",strtotime("-1 day"));
            $advertiser_id = OpAccount::where('id',$v['acc_id'])->value('name_id');
            $headers = array( 'Access-Token:'.$v['access_token']);
            $url = 'https://ad.oceanengine.com/open_api/2/advertiser/fund/daily_stat/?advertiser_id='.$advertiser_id.'&start_date='.$t.'&end_date='.$t;
            
            $rs = json_decode(http_get($url,$headers),true);
            if($rs['code'] == 0){
                // $arr['cost'] = $rs['data']['list'][0]['cost'];
                // $arr['convert'] = $rs['data']['list'][0]['convert'];
                // $arr['time'] = strtotime($t);
                // $arr['advertiser_id'] = $rs['data']['list'][0]['advertiser_id'];
                dump($rs['data']['list'][0]['balance']);
                dump($rs['data']['list']);
                //$this->add_xiaohao($arr);
    
            }else{
                // echo '<br>'.$rs['message'];
                // Log::write($advertiser_id.'字节获取账户消耗：开始','info');
                // Log::write($rs['message'],'info');
                // Log::write($advertiser_id.'字节获取账户消耗：结束','info');
                dump($rs['message']);
            }
        }
    
    
    }
    public function cs_get_acc_money(){
        set_time_limit(0);
        $t = strtotime(date("Y-m-d",strtotime("-1 day")));
        $w[] = ['currency','>',0];
        $w[] = ['time','=',$t];
        $w[] = ['consume_profit','=',''];
        $list = ItemConsume::where($w)->select();
        if(count($list)>0){
            foreach ($list as $k=>$v){
                $v['consume_profit'] = $this->get_profit($v['items_id'],$v['currency']);
                //dump($v);
                $this->get_add_xiaohao($v);
            }
        }else{
            echo '<br>时间：'.date("Y-m-d",$t).'没有新数据';
        }
    
    
    }
    
    
    
    
    
    
    
    
    
    //获取字节 表单消耗和数量
    public function zj_form_num(){
        set_time_limit(0);
        $wh[] = ['group','=','ziapi'];
        $list = Token::where($wh)->select();
        foreach ($list as $k=>$v){
            if($this->is_zj_acc_status($v['acc_id']) == false){
                continue;
            }
            $t = date("Y-m-d",strtotime("-1 day"));
            $advertiser_id = OpAccount::where('id',$v['acc_id'])->value('name_id');
            $headers = array( 'Access-Token:'.$v['access_token']);
            $url = 'https://ad.oceanengine.com/open_api/2/report/advertiser/get/?advertiser_id='.$advertiser_id.'&start_date='.$t.'&end_date='.$t;
            $rs = json_decode(http_get($url,$headers),true);
            if($rs['code'] == 0){
                $arr['cost'] = $rs['data']['list'][0]['cost'];
                $arr['convert'] = $rs['data']['list'][0]['convert'];
                $arr['time'] = strtotime($t);
                $arr['advertiser_id'] = $rs['data']['list'][0]['advertiser_id'];
                $arr['balance'] = $this->get_zj_balance($headers,$advertiser_id,$t);
                // dump($arr);
                $this->add_xiaohao($arr);
                
            }else{
                echo '<br>'.$rs['message'];
                Log::write($advertiser_id.'字节获取账户消耗：开始','info');
                Log::write($rs['message'],'info');
                Log::write($advertiser_id.'字节获取账户消耗：结束','info');
               // dump($rs['message']);
            }
        }   
    } 
    //判断账户，是否在跑
    function is_zj_acc_status($id){
        $wh[] = ['status','=',1];
        $wh[] = ['is_finish','=',0];
        $wh[] = ['op_account_id','=',$id];
        $r = Items::where($wh)->find();
        if($r){
            return true;
        }else{
            return false;
        }
    }
    //获取字节 昨天结余
    public function get_zj_balance($headers,$advertiser_id,$t){
        $url = 'https://ad.oceanengine.com/open_api/2/advertiser/fund/daily_stat/?advertiser_id='.$advertiser_id.'&start_date='.$t.'&end_date='.$t;
        
        $rs = json_decode(http_get($url,$headers),true);
        if(count($rs['data']['list']) > 0 && $rs['code'] == 0){
            return $rs['data']['list'][0]['balance'];
        }else{
            return 0;
        }
    }
    //添加消耗,编辑数据
    function add_xiaohao($data){
        set_time_limit(0);
        $rs = ViewItem::where('name_id',$data['advertiser_id'])->find();
        $da['items_id'] = $rs['item_id'];
        $da['currency'] = $data['cost'];
        $da['time'] = $data['time'];
        $da['balance'] = $data['balance'];
        $da['operation_id'] = $rs['operate_id'];
        $da['op_account_id'] = $rs['acc_id'];
        if($rs['type'] == 2){
            $da['num'] = $data['convert'];  //表单数量
        }
        $da['is_operate'] = $rs['operate_type'];
       
        $w[] = ['items_id' ,'=',$rs['item_id']];
        $w[] = ['time' ,'=',$data['time']];
        $r = ItemConsume::where($w)->find();
        if(empty($r)){
            try {
                //判断当天是否有切户，有切换账户，获取切换账户消耗
                $c = $this->is_zj_qiehu($rs['item_id'],$data['time'],$rs['acc_id']);
                if($c){
                    $da['currency'] = $data['cost'] - $c;
                }
                
                ItemConsume::create($da);
                echo '<br>账户ID：'.$data['advertiser_id'].' 时间：'.date("Y-m-d",$data['time']).'添加成功';
            } catch (\Exception $e) {
                echo '<br>账户ID：'.$data['advertiser_id'].' 时间：'.date("Y-m-d",$data['time']).'添加失败，'.$e->getMessage();
                Log::write($data['advertiser_id'].'字节获取账户消耗：开始','info');
                Log::write($e->getMessage(),'info');
                Log::write($data['advertiser_id'].'字节获取账户消耗：结束','info');
            }
        }else{
            echo '<br>时间：'.date("Y-m-d",$data['time']).'没有添加数据';
        } 
    }
    //判断当天是否有切户，有切换账户，获取切换账户消耗
    function is_zj_qiehu($items_id,$time,$op_account_id){
        $w[] = ['items_id' ,'<>',$items_id];
        $w[] = ['time' ,'=',$time];
        $w[] = ['op_account_id' ,'=',$op_account_id];
        $r = ItemConsume::where($w)->find();
        if($r){
            return $r['currency'];
        }else{
            return false;
        }
        
    }
   
    /* 计算消耗利润，跟新账户余额，和相关账户币累计
     * 
     *  */
    public function get_acc_money(){
        set_time_limit(0);
        $t = strtotime(date("Y-m-d",strtotime("-1 day")));
        $w[] = ['currency','>',0];
        $w[] = ['time','=',$t];
        $w[] = ['consume_profit','=',null];
        $list = ItemConsume::where($w)->select();
        
        if(count($list)>0){
            foreach ($list as $k=>$v){
                $this->get_add_xiaohao($v);
            }
        }else{
            echo '<br>时间：'.date("Y-m-d",$t).'没有新数据';
        }
        
    }
   
    ////添加消耗(2)
    function get_add_xiaohao($data){
        set_time_limit(0);
        Db::startTrans();
        try {
            $arr = $this->get_save_rebates($data['items_id'],$data['currency']);
            $d['consume_profit'] = $arr['profit'];
            $d['rebate'] = $arr['rebate'];
            $d['channel_rebate'] = $arr['channel_rebate'];
            $d['id'] = $data['id'];
            $d['update_time'] = time();
            $d['currency'] = $data['currency'];
            //dump($d);
            //添加消耗利润
            Db::name('item_consume')->save($d);
            //跟新项目消耗累计
            Db::name('items')->where('id', $data['items_id'])->inc('total_money', $data['currency']*1) ->update();
           
            Db::name('items')->where('id', $data['items_id'])->update(['end_time'=>time()]);
            //跟新客户累计账户币消耗
            $cu_id = Items::where('id',$data['items_id'])->value('customer_id');
            Db::name('customer')->where('id',$cu_id)->inc('total_currency_consume', $data['currency']*1) ->update();
            // 提交事务
            Db::commit();
            echo '跟新账户消耗完成';
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            echo $e->getMessage();
        }
    }
    function get_save_rebates($id,$currency){
        $wh['status'] = 1;
        $wh['type'] = 2;
        $wh['items_id'] = $id;
        $rs = Recharge::field('rebate,channel_rebate,currency')->where($wh)->order('update_time desc')->find();
       
        if($rs){
            $profit = cny_profit($currency, $rs['rebate'], $rs['channel_rebate']);
            if($profit < 0 ){
                $profit = 0;
            }
            $arr['rebate'] = $rs['rebate'];
            $arr['channel_rebate'] = $rs['channel_rebate'];
            $arr['profit'] = $profit;
        }else{
            $arr['rebate'] = 0;
            $arr['channel_rebate'] = 0;
            $arr['profit'] = 0;
        }
    
        return $arr;
    }
    
    
    
    //获取字节跳动余额
    public function get_acc_balance(){
        set_time_limit(0);
        $wh[] = ['group','=','ziapi'];
        $list = Token::where($wh)->select();
        foreach ($list as $k=>$v){
            $advertiser_id = OpAccount::where('id',$v['acc_id'])->value('name_id');
            $headers = array( 'Access-Token:'.$v['access_token']);
            $url = 'https://ad.oceanengine.com/open_api/2/advertiser/fund/get/?advertiser_id='.$advertiser_id;
            $rs = json_decode(http_get($url,$headers),true);
            if($rs['code'] == 0){
                $this->save_acc_balance($rs['data']);
                //dump($rs['data']);
            }else{
                echo '<br>\n'.$rs['message'];
                Log::write($advertiser_id.'字节获取账户消耗：开始','info');
                Log::write($rs['message'],'info');
                Log::write($advertiser_id.'字节获取账户消耗：结束','info');
                // dump($rs['message']);
            }
        }
    }
    //跟新账户余额
    function save_acc_balance($data){
        if(!empty($data)){
            try {
                $wh['name_id'] = $data['advertiser_id'];
                $da['balance'] = $data['valid_balance'];
                OpAccount::update($da,$wh);
                echo '<br>\n账户ID：'.$data['advertiser_id'].' 时间：'.date("Y-m-d",time()).'跟新账户余额成功'.$data['valid_balance'];
            } catch (\Exception $e) {
                echo '<br>\n账户ID：'.$data['advertiser_id'].' 时间：'.date("Y-m-d",time()).'更新余额失败，'.$e->getMessage();
                Log::write($data['advertiser_id'].'字节获取账户余额：开始','info');
                Log::write($e->getMessage(),'info');
                Log::write($data['advertiser_id'].'字节获取账户余额：结束','info');
            }
    
        }
    
    }

     
}
